package com.mediocre.eg7publisherconfirms;

import com.mediocre.constant.Constants;
import com.mediocre.util.CommonUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 该类用于测试发布的消息被confirm之后，消费者去消费这些消息
 * 该类不是教程中的，是我自己写的
 *
 * 经过测试，确认一件事：publisher confirms功能，是broker收到消息后的返回给生产者的一个确认消息，此时消费者还没处理或没处理完该消息
 *
 * 消费者
 */
public class RecvDirectTest {

    public static void main(String[] args) throws IOException, TimeoutException {
        final Channel channel = CommonUtils.getChannel();

        channel.exchangeDeclare(Constants.EXCHANGE_NAME_DIRECT, BuiltinExchangeType.DIRECT);

        String queueName = channel.queueDeclare().getQueue();

        channel.queueBind(queueName, Constants.EXCHANGE_NAME_DIRECT, Constants.ROUTING_KEY);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] received '" + message + "'");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        // autoAck此处为true，表示是自动确认的
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}
